package com.nanfang51g3.ckz.ui.share;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.nanfang51g3.ckz.R;
import com.nanfang51g3.ckz.application.CkzApplication;
import com.nanfang51g3.ckz.receiver.NetReceiver;
import com.nanfang51g3.ckz.ui.base.IPresenter;
import com.nanfang51g3.ckz.ui.base.Base2Activity;
import com.nanfang51g3.ckz.ui.login.LoginActivity;
import com.nanfang51g3.ckz.ui.webView.PublicWebView;
import com.nanfang51g3.ckz.ui.webView.webviewcallback.HostJsScope;
import com.nanfang51g3.ckz.ui.webView.webviewcallback.InjectedChromeClient;
import com.nanfang51g3.ckz.utils.AppManager;
import com.nanfang51g3.ckz.utils.EasyToast;
import com.nanfang51g3.ckz.utils.KLog;
import com.nanfang51g3.ckz.utils.NetUtils;
import com.nanfang51g3.ckz.utils.SPUtil;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.json.JSONObject;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/4/19.
 */
public class ShareTuiActivity extends Base2Activity implements ShareTuiContract.View, NetReceiver.NetEventHandle {
    ShareTuiContract.ShareTuiActionsListener shareActionsListener;
    @Bind(R.id.index_tv_title)
    TextView indexTvTitle;
    @Bind(R.id.tv_share)
    TextView tvShare;
    @Bind(R.id.linear_share_bottom)
    LinearLayout linearShareBottom;
    @Bind(R.id.tv_share_price)
    TextView tvSharePrice;
    int displayWidth = 0;
    int displayHeight = 0;
    private String assets_url = "file:///android_asset/web_error.html";
    private String assets_succes_url = "file:///android_asset/web_success.html";
    private WebSettings webSettings;
    @Bind(R.id.share_progressBar)
    ProgressBar shareProgressBar;
    @Bind(R.id.share_web_view)
    WebView shareWebView;

    private String id_image_url;
    private String id_title;
    private String id_price;
    private String id_url;
    private String id_content;
    private String id_id;
    private Context context;

    private String id_share_url;

    AlertDialog alertDialog;


    /**
     * 联网问题
     */
    private boolean networkBoolean = false;

    @Override
    public IPresenter getPresenter() {
        return null;
    }
    @Override
    public int getContentView() {
        return R.layout.share;
    }

    @Override
    public boolean isShowLeftIcon() {
        return true;
    }

    @Override
    public boolean isShowRightIcon() {
        return true;
    }

    @Override
    public int setLeftIcon() {
        return R.mipmap.ic_accounting_left;
    }

    @Override
    public int setRightIcon() {
        return R.mipmap.ic_accounting_doubt;
    }

    @Override
    public int showTitle() {
        return R.string.str_share;
    }

    @Override
    public void onClickLeft(View v) {
        AppManager.getAppManager().finishActivity(this);
    }

    @Override
    public void onClickRight(View v) {
        startActivity(new Intent(this, PublicWebView.class).putExtra("id_url", "http://ckt.51g3.com/help.php?app=0").putExtra("id_title", R.string.str_me_about));
    }


    @Override
    public void success(boolean msgBoolean, String idShareUrl) {
        KLog.i("Evd", "success");
        if (msgBoolean) {
            this.id_share_url = idShareUrl;
            shareUrl();
            KLog.i("Evd","if  = "+id_share_url);
        } else {
            this.id_share_url = id_url;
            KLog.i("Evd","else  = "+id_share_url);
        }

    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public void onIntent() {
        super.onIntent();
        id_url = getIntent().getStringExtra("id_url");
        id_title = getIntent().getStringExtra("id_title");
        id_price = getIntent().getStringExtra("id_price");
        id_content = getIntent().getStringExtra("id_content");
        id_image_url = getIntent().getStringExtra("id_image_url");
        id_id = getIntent().getStringExtra("id_id");
        id_share_url = getIntent().getStringExtra("id_url");

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        shareActionsListener = DaggerShareTuiContractComponent
                .builder()
                .appComponent(CkzApplication.getAppComponent())
                .shareTuiPresenterModule(new ShareTuiPresenterModule(this))
                .build().getShareTuiPresenter();
        Log.i("TAG", shareActionsListener == null ? "shareActionsListener==null" : "shareActionsListener!=null");
        ButterKnife.bind(this);
        shareProgressBar.setMax(100);
        shareWebView.loadUrl(id_url);
        setWebView();
        indexTvTitle.setText(id_title);
        tvSharePrice.setText(id_price);
        NetReceiver.ehList.add(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        NetReceiver.ehList.remove(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    public void setWebView() {
        webSettings = shareWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAllowFileAccess(true);// 设置允许访问文件数据
        webSettings.setUseWideViewPort(true);//点击操作扩大缩小
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setBuiltInZoomControls(true);//缩小指针
        webSettings.setDatabaseEnabled(true);
        CustomChromeClient customChromeClient = new CustomChromeClient("injs", HostJsScope.class);
        shareWebView.setWebChromeClient(customChromeClient);
        shareWebView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                shareProgressBar.setVisibility(View.VISIBLE);
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                shareWebView.loadUrl(assets_url);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                super.onReceivedSslError(view, handler, error);
            }
        });
    }

    /**
     * 继承Injected 必须重写的方法
     */
    class CustomChromeClient extends InjectedChromeClient {
        public CustomChromeClient(String injectedName, Class injectedCls) {
            super(injectedName, injectedCls);
            // TODO Auto-generated constructor stub
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message,
                                 final JsResult result) {
            // TODO Auto-generated method stub
            return super.onJsAlert(view, url, message, result);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            // TODO Auto-generated method stub
            KLog.i("E", shareProgressBar == null ? "shareProgressBar=1" : "shareProgressBar=0");
            if (shareProgressBar != null) {
                shareProgressBar.setProgress(newProgress);
                if (newProgress >= 100) {
                    shareProgressBar.setVisibility(View.GONE);
                }
            }
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message,
                                  String defaultValue, JsPromptResult result) {
            // TODO Auto-generated method stub
            try {
                JSONObject json = new JSONObject(message);
                KLog.i("Evd", json.toString());//获取数据判断调用js方法
                if (json.optString("method").equals("reloadWebView")) {
                    if (NetUtils
                            .checkNetworkInfo(getContext())) {
                        shareWebView.loadUrl(id_url);
                    } else {
                        Toast.makeText(getContext(), "您的网络已断开,请重新连接网络",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();

            } finally {

            }

            return super.onJsPrompt(view, url, message, defaultValue, result);
        }
    }


    public String getShareTitle(String platform) {
        switch (platform) {
            case "QQ":
                return "QQ";
            case "QZONE":
                return "QQ空间";
            case "WEIXIN":
                return "微信";
            case "WEIXIN_CIRCLE":
                return "朋友圈";

        }
        return "error";

    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {
            KLog.d("plat", "onResult" + platform);
            Toast.makeText(ShareTuiActivity.this, getShareTitle(platform + "") + " 分享成功啦", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            KLog.d("plat", "onError" + platform);
            Toast.makeText(ShareTuiActivity.this, getShareTitle(platform + "") + " 分享失败啦", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            KLog.d("plat", "onCancel" + platform);
            Toast.makeText(ShareTuiActivity.this, getShareTitle(platform + "") + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };

    AlertDialog shareAlertDialog;

    public void shareUrl() {
        KLog.i("Evd","shareUrl"+id_share_url);
        boolean is_login = (boolean) SPUtil.get(this, "is_login", false);
        if (is_login) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            LayoutInflater inflater = LayoutInflater.from(this);
            View layout = inflater.inflate(R.layout.share_app_progress_bar_dialog, null);
            builder.setView(layout);
            builder.setCancelable(true);
            shareAlertDialog = builder.create();
            shareAlertDialog.show();
            layout.findViewById(R.id.tv_share_determine).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    shareAlertDialog.dismiss();
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    Uri content_url = Uri.parse(id_share_url);
                    intent.setData(content_url);
                    startActivity(intent);
                }
            });
            layout.findViewById(R.id.tv_share_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    shareAlertDialog.dismiss();
                }
            });

//            shareProgressBarDialog = new ShareProgressBarDialog(this, R.style.share_progress_bar_style);
//            shareProgressBarDialog.setListener(new ShareCancelDetermineListener("", ""));
//            shareProgressBarDialog.show();
//            shareProgressBarDialog.setCanceledOnTouchOutside(false);
//            ProgressDialog dialog = new ProgressDialog(ShareTuiActivity.this);
//            dialog.setTitle("创客推");
//            dialog.setMessage("你正在使用创客推分享信息");
//            Config.dialog = dialog;
//            KLog.i("Evd", "shareUrl=" + id_share_url);
//            UMImage image = new UMImage(ShareTuiActivity.this, id_image_url);
//            ShareUtils.getInstance(ShareTuiActivity.this).open(ShareTuiActivity.this, umShareListener, image, id_title, id_content, id_share_url);

        } else {
//            EasyToast.showShort(this, "你还未登录哦,请先登录");
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            LayoutInflater inflater = LayoutInflater.from(this);
            View layout = inflater.inflate(R.layout.alert_share, null);
            builder.setView(layout);
            builder.setCancelable(true);
            alertDialog = builder.create();
            alertDialog.show();
            layout.findViewById(R.id.tv_alert_login).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alertDialog.dismiss();
                    startActivity(new Intent(ShareTuiActivity.this, LoginActivity.class));
                }
            });
            layout.findViewById(R.id.tv_alert_share).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alertDialog.dismiss();
                    if (shareAlertDialog == null) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(ShareTuiActivity.this);
                        LayoutInflater inflater = LayoutInflater.from(ShareTuiActivity.this);
                        View layout = inflater.inflate(R.layout.share_app_progress_bar_dialog, null);
                        builder.setView(layout);
                        builder.setCancelable(true);
                        shareAlertDialog = builder.create();
                        shareAlertDialog.show();
                        layout.findViewById(R.id.tv_share_determine).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                shareAlertDialog.dismiss();
                                Intent intent = new Intent();
                                intent.setAction("android.intent.action.VIEW");
                                Uri content_url = Uri.parse(id_share_url);
                                intent.setData(content_url);
                                startActivity(intent);
                            }
                        });
                        layout.findViewById(R.id.tv_share_cancel).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                shareAlertDialog.dismiss();
                            }
                        });
                    } else {
                        shareAlertDialog.show();
                    }

                }
            });
            layout.findViewById(R.id.tv_alert_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alertDialog.dismiss();
                }
            });

        }

    }

    @OnClick(R.id.tv_share)
    public void tv_share(View view) {
        if (!NetUtils.checkNetworkInfo(this)) {
            EasyToast.showShort(this, "网络连接失败,请打开网络连接!");
            return;
        }
        boolean is_login = (boolean) SPUtil.get(this, "is_login", false);
        if (is_login) {
            KLog.i("Evd", "is_login = " + is_login);
            KLog.i("Evd", id_url + "-" + id_share_url);
            if (id_url.equals(id_share_url)) {

                /**
                 * 获取分享加密的url
                 * @see ShareTuiPresenter#requestUrl(String)
                 */
                shareActionsListener.requestUrl(id_id);
            } else {
                shareUrl();
            }
        } else {
            shareUrl();
        }
    }

    @Override
    public void netState(NetReceiver.NetState netCode) {
        switch (netCode) {
            case NET_NO:
                KLog.e("JK", "没有网络连接");
                break;
            case NET_2G:
                KLog.e("JK", "2g网络");
                shareWebView.loadUrl(id_url);
                break;
            case NET_3G:
                KLog.e("JK", "3g网络");
                shareWebView.loadUrl(id_url);
                break;
            case NET_4G:
                KLog.e("JK", "4g网络");
                shareWebView.loadUrl(id_url);
                break;
            case NET_WIFI:
                KLog.e("JK", "WIFI网络");
                shareWebView.loadUrl(id_url);
                break;
            case NET_UNKNOWN:
                KLog.e("JK", "未知网络");
                break;
            default:
                KLog.e("JK", "不知道什么情况~>_<~");
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);//解除绑定，官方文档只对fragment做了解绑
    }
}
